package org.amos.security.handler;

import cn.hutool.core.lang.Dict;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.exception.ServiceException;
import org.amos.security.api.UserAuthApi;
import org.amos.security.authentication.Authenticator;
import org.amos.security.constants.AuthConstant;
import org.amos.security.constants.AuthTypeEnums;
import org.amos.security.domain.bo.AuthInfo;
import org.amos.security.utils.PwdUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@RequiredArgsConstructor
public class AccountAuthHandler implements Authenticator {

    public static final Integer AUTH_TYPE = AuthTypeEnums.ACCOUNT.getCode();
    private final UserAuthApi userAuthApi;

    @Override
    public AuthInfo authenticate(Dict param) {
        String username = param.getStr(AuthConstant.USER_NAME);
        String password = param.getStr(AuthConstant.PASSWORD);
        // 执行认证
        AuthInfo authInfo = userAuthApi.getUserByAccount(username);
        // 用户状态检查
        if (Objects.isNull(authInfo) || !PwdUtils.match(password, authInfo.getPassword())) {
            throw new ServiceException("账号或密码有误!");
        }
        return authInfo;
    }

    @Override
    public Integer authType() {
        return AUTH_TYPE;
    }

    @Override
    public void preHandle() throws Exception {

    }

    @Override
    public void afterCompletion() throws Exception {

    }
}
